import React, { useState } from 'react';
import '../css/xi.css';
import { Cell, List, PullRefresh } from 'react-vant';
import { history } from 'umi';
import axios from 'axios';

export default function xihuan() {
  const [xihuanlist, setxilist] = useState([]);
  const [finisheds, setFinisheds] = useState(false);
  const [getlist, setgetlist] = useState();

  async function getData(throwError) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        if (throwError) {
          reject(new Error('error'));
        } else {
          fetch('http://localhost:3000/yrt/xihuanlist')
            .then((response) => response.json())
            .then((data) => resolve(data))
            .catch((err) => reject(err));
        }
      }, 1000);
    });
  }
  // 下拉刷新
  const onLoad = async (isRefresh) => {
    const data = await getData();
    setxilist((v) => {
      const newList = isRefresh ? data.data : [...v, ...data.data];
      if (newList.length >= 15) {
        setFinisheds(true);
      }
      return newList;
    });
  };
  const onRefresh = async () => {
    setFinisheds(false);
    await onLoad(5);
  };

  const xiang = (obj) => {
    setgetlist(obj);
    history.push({ pathname: '/duixihuan', state: { ...obj } });
  };

  return (
    <div style={{ width: '100%' }}>
      <PullRefresh onRefresh={onRefresh}>
        <List
          finished={finisheds}
          onLoad={onLoad}
          loadingText="加载中..."
          finishedText="没有更多了,抱歉…"
        >
          {xihuanlist.map((item, index) => (
            <Cell
              style={{
                display: 'inline-block',
                width: '50%',
                paddingLeft: '0px',
              }}
              key={index}
              title={
                <div key={index} className="xibody">
                  <img src={item.img} alt="" onClick={() => xiang(item)} />
                  <p style={{ marginBottom: 0 }}> {item.title}</p>
                  <p> {item.price}</p>
                </div>
              }
            />
          ))}
        </List>
      </PullRefresh>
    </div>
  );
}
